<script setup>
import _ from 'lodash'
import {isMbRoot, isGroup, isApp, canEdit} from './common.js';
import mbformMb from './mbform-mb.vue';
import {computed, nextTick, onMounted, reactive, ref, toRefs, watch} from "vue";
import {api} from "@jzl/api";
import {$jui} from '@jzl/utils'
import {ResizeObserver} from 'vue3-resize'
import {DFT_ICONS} from "@jzl/icons";

const props = defineProps({
  currentData: {
    type: Object,
    default: {}
  }
})

const {
  loading,
  selectedData,

  actionType,     // createOption | createOptionBefore | createOptionChild | edit
  datasTableHeight,

  options,

  formOptionWinName,
  formOptionWinShow,
} = toRefs(reactive({
  loading: false,
  selectedData: null,

  actionType: 'view',     // createOption | createOptionBefore | createOptionChild | edit
  datasTableHeight: 500,

  options: [],

  formOptionWinName: '',
  formOptionWinShow: false,
}))

const datasContainerRef = ref(null)

const appId = computed(() => {
  if (!props.currentData) return -1;

  if (isApp(props.currentData)) {
    return _.get(props.currentData, 'group_id') || _.get(props.currentData, 'id');
  } else if (isGroup(props.currentData)) {
    return _.get(props.currentData, 'app_id');
  } else if (isMbRoot(props.currentData)) {
    return _.get(props.currentData, 'mb_id');
  }

  return -1;
})

const mbGroupId = computed(() => {
  if (isApp(props.currentData)) {
    return -1;
  } else if (isGroup(props.currentData)) {
    return _.get(props.currentData, 'mb_group_id');
  } else if (isMbRoot(props.currentData)) {
    return _.get(props.currentData, 'mb_group_id');
  }

  return -1;
})

watch(() => props.currentData, (val) => {
  if (isMbRoot(val)) {
    handleResize();
    loadOptions();
  }
}, {deep: true})

onMounted(() => {
  init()
})

const init = () => {
  handleResize();
}

const handleResize = () => {
  nextTick(() => {
    if (!datasContainerRef.value) return;

    let rect = datasContainerRef.value.getBoundingClientRect();
    let height = _.get(rect, 'height');
    if (height > 0) {
      datasTableHeight.value = height;
    }
  });
}

const loadOptions = async () => {
  if (!props.currentData) return;

  if (props.currentData.datas) {
    options.value = props.currentData.datas;
    return;
  }

  loading.value = true;

  let mb = null;
  if (props.currentData.mb_id) {
    mb = await api.mb.getMbById(props.currentData.mb_id);
  }

  loading.value = false;

  if (!mb) return;

  options.value = mb.subs;
}

const handleShowCreateOption = () => {
  let name = _.get(props.currentData, 'name');

  selectedData.value = props.currentData;
  actionType.value = 'createOption';
  formOptionWinName.value = `【${name}】码表下新增选项`;
  formOptionWinShow.value = true;
}

const handleShowCreateOptionChild = (option) => {
  let name = _.get(option, 'name');

  selectedData.value = option;
  actionType.value = 'createOptionChild';
  formOptionWinName.value = `【${name}】选项下新增子选项`;
  formOptionWinShow.value = true;
}

const handleShowCreateOptionBefore = (option) => {
  let name = _.get(option, 'name');

  selectedData.value = option;
  actionType.value = 'createOptionBefore';
  formOptionWinName.value = `【${name}】选项前新增选项`;
  formOptionWinShow.value = true;
}

const handleFormClose = async (isUpdate) => {
  formOptionWinShow.value = false;

  if (isUpdate) {
    props.currentData.datas = null;
    await loadOptions();
  }
}

const handleOptionUp = async (option) => {

  if (!option) return;

  loading.value = false;

  let id = option.mb_id;
  let ret = await api.mb.mbMoveUp(id);

  if (ret) {
    await handleFormClose(true);
  }

  loading.value = false;
}

const handleOptionDown = async (option) => {
  if (!option) return;

  loading.value = true;

  let id = option.mb_id;
  let ret = await api.mb.mbMoveDown(id);

  if (ret) {
    await handleFormClose(true);
  }

  loading.value = false;
}

const handleOptionEdit = (option) => {
  let name = _.get(option, 'name');

  selectedData.value = option;
  actionType.value = 'edit';
  formOptionWinName.value = `【${name}】选项修改`;
  formOptionWinShow.value = true;
}

const handleOptionRemove = (option) => {
  let dt = option;

  if (!dt) return;

  let isMbGroup = isGroup(dt);
  let msg = `确定删除${isMbGroup ? '目录' : '码表选项'}【${dt.name}】?`;
  $jui.confirm(msg).then(async () => {
    let ret = null;

    loading.value = true;

    if (isMbGroup) {
      ret = await api.mb.removeMbGroup(dt.mb_group_id);
    } else {
      ret = await api.mb.removeMb(dt.mb_id);
    }

    await handleFormClose(true);

    loading.value = false;
  }).catch(e => {
    loading.value = false;
  });
}

const handleImportChange = () => {
  emit('mb-change');
}

const handleDownMbList = () => {
  $utils.downloadFileStatic("/assets/tpl/import_tpl_mb.xlsx");
}

</script>

<template>
  <div
    class="mb-info"
    v-jloading="loading"
    v-if="currentData">
    <div class="mb-detail">
      <div class="mb-detail-hd-icon">
        <JIcon
          v-if="currentData.id === -100"
          :icon="DFT_ICONS.platform"
        />
        <JIcon
          v-else-if="currentData.id === -1"
          :icon="DFT_ICONS.global"
          class="fa fa-google"></JIcon>
        <JIcon
          v-else-if="isApp(currentData)"
          :icon="DFT_ICONS.app"
        />
        <JIcon
          v-else-if="isGroup(currentData)"
          :icon="DFT_ICONS.dir"
        ></JIcon>
        <template v-else-if="isMbRoot(currentData)">
          <JIcon
            v-if="currentData.type === 'TREE'"
            :icon="DFT_ICONS.tree"
          />
          <JIcon
            v-else
            :icon="DFT_ICONS.mb"
          />
          <!--<img src="/assets/images/filetype/small/GeneralType.png" />-->
        </template>
      </div>
      <div class="mb-detail-hd-info">
        <div class="mb-detail-hd-title">{{ currentData.name }}</div>
        <div class="mb-detail-hd-mark">{{ currentData.mb_code }}</div>
      </div>

      <template v-if="canEdit(currentData)">
        <el-button
          size="small"
          type="text"
          :disabled="actionDisabled"
          style="margin-right:10px;"
          @click="handleDownMbList()">
          <template #icon>
            <JIcon :icon="DFT_ICONS.download"></JIcon>
          </template>
          下载模板
        </el-button>
        <data-import-btn
          :menu-id="-1"
          :type="3"
          @import-change="handleImportChange"
          :params="{ appId, mbGroupId }"
        ></data-import-btn>
      </template>
      <el-button
        class="app-group-add-btn"
        type="text"
        size="small"
        style="margin-left: 10px;"
        v-if="isMbRoot(currentData) && canEdit(currentData)"
        @click="handleShowCreateOption()">
        <template #icon>
          <JIcon :icon="DFT_ICONS.add"></JIcon>
        </template>
        增加选项
      </el-button>
    </div>
    <template v-if="isMbRoot(currentData)">
      <div
        class="m-table-container"
        ref="datasContainerRef">
        <el-table
          :data="options"
          size="small"
          row-key="mb_id"
          :tree-props="{ children: 'subs' }"
          :height="datasTableHeight"
          class="m-table" indent="0"><!-- default-expand-all -->
          <el-table-column
            prop="name"
            label="名称">
            <template #header="scope">
              <span style="display:inline-block;width:25px;height:20px;"></span>名称
            </template>
            <template #default="scope">
              <span
                style="display:inline-block;width:20px;height:20px;"
                v-if="!scope.row.subs || !scope.row.subs.length"></span>
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column prop="mb_code" label="编码" width="220">
            <template #default="scope">
              <span
                v-copy="scope.row.mb_code"
                v-text="scope.row.mb_code"
                v-tippy="{ arrow: true, placement: 'right' }"
                content="点击复制"></span>
            </template>
          </el-table-column>
          <!--<el-table-column prop="mb_code_alias" label="外编码"></el-table-column>
          <el-table-column prop="alias" label="别名"></el-table-column>-->
          <el-table-column prop="remark" label="备注"></el-table-column>
          <el-table-column
            prop="remark"
            label="操作"
            width="165"
            align="center"
            v-if="canEdit(currentData)">
            <template #default="scope">
              <el-button
                size="small"
                type="text"
                v-tippy
                content="向上"
                @click="handleOptionUp(scope.row)"
              >
                <template #icon>
                  <JIcon :icon="DFT_ICONS.arrowUp"></JIcon>
                </template>
              </el-button>
              <el-button
                size="small"
                type="text"
                v-tippy
                content="向下"
                @click="handleOptionDown(scope.row)">
                <template #icon>
                  <JIcon :icon="DFT_ICONS.arrowDown"></JIcon>
                </template>
              </el-button>
              <el-button
                size="small"
                type="text"
                v-tippy
                content="修改"
                @click="handleOptionEdit(scope.row)"
              >
                <template #icon>
                  <JIcon :icon="DFT_ICONS.edit"></JIcon>
                </template>
              </el-button>
              <el-button
                size="small"
                type="text"
                v-tippy
                content="删除"
                @click="handleOptionRemove(scope.row)">
                <template #icon>
                  <JIcon :icon="DFT_ICONS.delete"></JIcon>
                </template>
              </el-button>
              <el-button
                size="small"
                type="text"
                v-tippy
                content="上面增加选项"
                @click="handleShowCreateOptionBefore(scope.row)"
              >
                <template #icon>
                  <JIcon :icon="DFT_ICONS.add"></JIcon>
                </template>
              </el-button>
              <el-button
                size="small"
                type="text"
                v-tippy
                content="添加子选项"
                v-if="currentData && currentData.type === 'TREE'"
                @click="handleShowCreateOptionChild(scope.row)"
              >
                <template #icon>
                  <JIcon :icon="DFT_ICONS.addCircle"></JIcon>
                </template>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>
    <div v-else class="mb-group-info">
      <div class="mb-group-title" v-text="currentData.name"></div>
      <div v-if="currentData && currentData.subs">{{ currentData.subs.length }}</div>
    </div>

    <el-dialog
      :title="formOptionWinName"
      v-model="formOptionWinShow"
      :close-on-click-modal="false"
      :append-to-body="true">
      <mbform-mb
        v-if="formOptionWinShow"
        :current-data="selectedData"
        :action-type="actionType"
        @close="handleFormClose"></mbform-mb>
    </el-dialog>
    <ResizeObserver @notify="handleResize"/>
  </div>
</template>

<style lang="scss">
.mb-group-info {
  height: 100%;
  display: flex;
  flex: 1;
  justify-content: center;
  align-items: center;
  flex-flow: column;
  background: #FFF;

  .mb-group-title {
    font-size: 18px;
    margin-bottom: 10px;
  }
}
</style>
